package com.its.common.config;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author xiaxp
 * @Date 2021-05-11 11:12
 * @Description
 */
@Slf4j
public class AsyncTaskQueue {
    private static final int THREAD_SIZE = Runtime.getRuntime().availableProcessors();

    private static final int QUEUE_SIZE = 5000;

    private static ExecutorService senderAsync =
            new ThreadPoolExecutor(THREAD_SIZE + 2,
                    THREAD_SIZE * 2 + 64,
                    60L,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<>(QUEUE_SIZE),
                    r -> {
                        Thread t = new Thread(r);
                        t.setName("async_task_handler");
                        return t;
                    },
                    (r, executor) -> log.error("async handler is error rejected, runnable: {}, executor: {}", r, executor));

    public static void handle(Runnable runnable) {
        senderAsync.submit(runnable);
    }
}
